<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :is-show-before="false">
        <template #after>
          <el-button
            type="primary"
            size="small"
            @click="$router.push('/employees/import')"
          >导入</el-button>
          <el-button
            type="primary"
            size="small"
            @click="onExport"
          >导出</el-button>

          <el-button
            type="primary"
            size="small"
            @click="addEmployeesDialogVisible = true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <!-- 表格 -->
      <!-- 放置表格和分页 -->
      <el-card style="margin: 10px 0">
        <el-table border :data="employeesList">
          <el-table-column label="序号" sortable type="index" />
          <el-table-column label="姓名" sortable prop="username" />
          <el-table-column label="头像" sortable>
            <template slot-scope="{row}">
              <img style="width:100px;height:100px" :src="row.staffPhoto" alt="" @click="qrCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable
            prop="formOfEmployment"
            :formatter="formatterType"
          />
          <el-table-column label="部门" sortable prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry">
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatTime }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable prop="enableState" />
          <el-table-column label="操作" sortable fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :page-size="query.size"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>

        <!-- 新增员工弹框 -->
        <add-employees
          :visible.sync="addEmployeesDialogVisible"
          @add-success="loadEmployeesList"
        />
      </el-card>

      <!-- // 点击显示头像二维码弹层 -->
      <el-dialog
        title="提示"
        :visible.sync="qrCodedialogVisible"
        width="30%"
      >
        <canvas ref="code" /></el-dialog>
    </div>
  </div>
</template>

<script>
import PageTools from '@/components/PageTools'
import { getEmployessListList } from '@/api/employess'
import obj from '@/api/constant/employees'
import AddEmployees from './component/add-employees.vue'
import QRCode from 'qrcode'
const { hireType } = obj
export default {
  name: 'Employees',
  components: { PageTools, AddEmployees },
  data() {
    return {
      query: {
        page: 1,
        size: 5
      },
      total: 2,
      employeesList: [],
      addEmployeesDialogVisible: false,
      qrCodedialogVisible: false
    }
  },

  created() {
    this.loadEmployeesList()
  },

  methods: {

    // 加载员工列表
    async  loadEmployeesList() {
      const res = await getEmployessListList(this.query)
      this.employeesList = res.rows
      this.total = res.total
    },

    handleCurrentChange(val) {
      this.query.page = val
      this.loadEmployeesList()
    },
    formatterType(row, column, cellValue, index) {
      const finditem = hireType.find(item => item.id === cellValue)
      return finditem ? finditem.value : '聘用形式错误'
    },
    // 点击导出
    onExport() {
      import('@/vendor/Export2Excel').then(async(excel) => {
        const { rows } = await getEmployessListList({
          page: 1,
          size: this.total
        })
        const headers = {
          '手机号': 'mobile',
          '姓名': 'username',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const header = Object.keys(headers)// ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
        // const data = rows.map(item => header.map(item2 => item[headers[item2]]))
        const data = rows.map(item => {
          // item:{mobile,username,timeOfEntry...}
          return header.map(item2 => {
            // item2=='姓名', '手机号'  headers[item2] ===mobile,username,timeOfEntry...
            if (item2 === '聘用形式') {
              const finditem = hireType.find(typeitem => item[headers[item2]] - 0 === typeitem.id)
              return finditem ? finditem.value : '未知'
            }
            return item[headers[item2]]
          })
        })
        console.log(data)
        excel.export_json_to_excel({

          header, // 表头 必填
          multiHeader: [['手机号', '其他', '', '', '', '', '部门']],
          merges: ['A1:A2', 'B1:F1', 'G1:G2'],
          data: data, // 具体数据 必填
          filename: 'excel-list', // 文件名非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 文件类型非必填
        })
      })
    },

    // 点击显示头像二维码
    qrCode(rowimg) {
      if (!rowimg) return this.$message.error('该用户未设置头像')
      // 在这一步 数据变了 数据驱动视图 但是数据驱动视图是异步的 要想直接在下面拿到ref 就必须用nexttick（回调）
      this.qrCodedialogVisible = true
      this.$nextTick(_ => {
        QRCode.toCanvas(this.$refs.code, rowimg)
      })
    }
  }
}
</script>

<style scoped lang="less"></style>
